// src/utils/WebSocket.js
export default class WebSocketService {
  constructor(url, userId) {
    this.url = `${url}${userId}`;
    this.socket = null;
    this.connect();
  }

  connect() {
    this.socket = new WebSocket(this.url);
    this.socket.onopen = this.onOpen.bind(this);
    this.socket.onmessage = this.onMessage.bind(this);
    this.socket.onerror = this.onError.bind(this);
    this.socket.onclose = this.onClose.bind(this);
  }

  onOpen(event) {
    console.log("WebSocket 已连接：", event);
  }

  onMessage(event) {
    console.log(event)
    console.log(event.data)
    const data = JSON.parse(event.data);
    this.handleMessage(data);
  }

  onError(event) {
    console.error("WebSocket 发生错误：", event);
  }

  onClose(event) {
    console.log("WebSocket 已关闭：", event);
  }

  sendMessage(message) {
    if (this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(message));
    } else {
      console.error("WebSocket 发生错误：", event);
      // 尝试获取更多信息
      console.error("WebSocket URL:", this.url);
      console.error("WebSocket ReadyState:", this.socket.readyState);
    }
  }

  handleMessage(data) {
    console.log("接收到消息：", data);
    // 在子类中实现消息处理逻辑
  }

  close() {
    if (this.socket) {
      this.socket.close();
    }
  }
}
